<template>
    <div class="com-date-range c-form-group">
        <label>{{ label }}</label>
        <input class="c-form-control c-daterange" type="text" ref="dateRange" readonly="readonly"/>
    </div>
</template>

<script>
    import '@/module/laydate';
    import { timeFormat, getDate, mytips } from '@/module/tools';
    export default {
        name: 'dateRange',
        mounted(){
            laydate.render({
                elem: this.$refs.dateRange,
                range: true,
                max: timeFormat(new Date(), 'yyyy-MM-dd'),
                done: (value, date) => {
                    if(this.spacingDay != 0){
                        let oldValue = this.$refs.dateRange.value;
                        let beginDate = value.split(' - ')[0];
                        let endDate = value.split(' - ')[1];
                        let beginTimestamp = Date.parse(beginDate);
                        let endTimestamp = Date.parse(endDate);
                        let spacingDay = ( endTimestamp - beginTimestamp ) / 3600 / 24 / 1000 + 1;
                        if( spacingDay > this.spacingDay ){
                            setTimeout(
                                () => {
                                    this.$refs.dateRange.value = oldValue;
                                    mytips('选择的日期间隔最多'+ this.spacingDay +'天')
                                }, 0
                            );
                        }
                    }
                }
            });

            if(typeof this.initValue == 'number'){
                let endDate = timeFormat(new Date(), 'yyyy-MM-dd');
                let startDate = Date.parse(new Date()) - this.initValue*24*3600*1000;
                startDate = timeFormat(new Date(startDate), 'yyyy-MM-dd');
                this.$refs.dateRange.value = startDate + ' - ' + endDate;
            }else{
                switch (this.initValue){
                    case 'currMonth':this.$refs.dateRange.value = timeFormat(new Date(), 'yyyy-MM-01 - yyyy-MM-dd');break;
                    default:         this.$refs.dateRange.value = this.initValue;
                }
            }

        },
        methods: {
            beginDate(){
                let dateRange = this.$refs.dateRange.value;
                return dateRange ? getDate(dateRange)[0] : '';
            },
            endDate(){
                let dateRange = this.$refs.dateRange.value;
                return dateRange ? getDate(dateRange)[1] : '';
            }
        },
        props: {
            label: { type: String, default: '时间：' },
            initValue: { default: 'currMonth' },
            spacingDay: { type: Number, default: 0 }
        }
    }
</script>
